import {
  Button,
  Row,
  Col,
  Space,
  Input
} from 'antd';

import { useHistory } from 'react-router-dom';
import { useState, useEffect, useCallback } from 'react';
import { useRequest } from 'ahooks';

import * as APIS from '../../constants/api-constants';
import Show from './components/show';

export default () => {
  const history = useHistory();
  const [tableProps, setTableProps] = useState<Questionnaire.Template[]>([]);
  const [title, setTitle] = useState('');
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const { run, loading } = useRequest((
    currentPage,
    pageSize,
    searchTitle?
  ) => ({
    url: APIS.TEMPLATE_LIST,
    method: 'GET',
    params: {
      page: currentPage,
      pageSize,
      title: searchTitle
    },
  }), {
    manual: true,
    onSuccess: (res) => {
      const { templateList } = res.data;
      setTableProps(templateList.rows);
      setTotal(templateList.count);
    },
    onError: (err) => {
      console.log(err);
    },
  });

  const requestTemplateList = useCallback(
    (pageNumber: number) => run(pageNumber, 10, title)
      .then(() => {
        setPage(pageNumber);
      }),
    [title]
  );

  useEffect(() => {
    requestTemplateList(1);
  }, []);

  return (
    <Space size={8} direction="vertical">
      <Row
        justify="space-between"
        align="top"
        gutter={[0, 16]}
      >
        <Col lg={5} sm={11} xs={24}>
          <Input
            allowClear
            placeholder="请输入问卷名称"
            onChange={(e) => {
              setTitle(e.target.value);
            }}
          />
        </Col>
        <Col lg={5} sm={11} xs={24} pull={4}>
          <Button
            type="primary"
            onClick={() => {
              requestTemplateList(1);
            }}
          >
            搜索问卷
          </Button>
        </Col>
        <Col lg={5} sm={11} xs={24}>
          <Button
            type="primary"
            onClick={() => {
              history.push('/home/templateIncrease');
            }}
          >
            添加问卷
          </Button>
        </Col>
      </Row>
      <Row
        justify="space-between"
        align="top"
        gutter={[0, 16]}
      >
        <Show
          currentPage={page}
          tableProps={tableProps}
          loading={loading}
          requestTemplateList={requestTemplateList}
          total={total}
        />
      </Row>
    </Space>
  );
};
